import { useMemo } from 'react';

import type { TagProps } from 'antd';
import { Tag } from 'antd';
import { observer } from 'mobx-react-lite';

import { useStore } from '@/store';

type DictProps = TagProps & {
  dicCode: string;
  value?: string | number | null | undefined;
};

const Dict: React.FC<DictProps> = ({ dicCode, value, ...rest }) => {
  const store = useStore();

  const render = useMemo(() => {
    if (store.dict) {
      const list = store.dict[dicCode] || [];

      const find = list.find((v) => {
        if (/\d+/.test(v.dicValue) && typeof value === 'number') {
          return Number(v.dicValue) === value;
        }

        return v.dicValue === value;
      });

      if (find) {
        return find;
      }
    }

    return null;
  }, [store.dict, dicCode, value]);

  if (render) {
    return (
      <Tag color={render.dicColour} {...rest}>
        {render.dicName}
      </Tag>
    );
  }

  return <Tag {...rest}>{value}</Tag>;
};

export default observer(Dict);
